package dt.bankAction;

import java.io.IOException;
import java.io.Reader;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.opensymphony.xwork2.ActionSupport;

import dt.member.memberVO;

public class OutAction extends ActionSupport implements SessionAware {

	private Map session;
	public static Reader reader;
	public static SqlMapClient sqlMapper;
	
	private AccountVO paramClass;
	private AccountVO resultClass;
	
	private static final long serialVersionUID = 1L;

	private String id;
	private int exchangeMoney;
	private int exchangeResult;
	private memberVO memClass;
	
	public OutAction() throws IOException {
		reader = Resources.getResourceAsReader("sqlMapConfig.xml");
		sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader); 
		reader.close();
	}
	
	public String form() {
		return SUCCESS;
	}
	
	public String execute() throws Exception {
		memClass = new memberVO();
		paramClass = new AccountVO();
		resultClass = new AccountVO();
		
		id = session.get("id").toString();
		memClass = (memberVO) sqlMapper.queryForObject("idCheck", id);
		
		if(memClass.getId() == null) {
			System.out.println("id가 존재 하지 않음");
			exchangeResult = 0;
			return ERROR;
		}
		else {
			
			System.out.println(memClass.getId());
			resultClass = (AccountVO)sqlMapper.queryForObject("account.select-account", memClass.getId());
			System.out.println("2");
			if(resultClass == null){
							
				exchangeResult = 2;
				return ERROR;
								
			} else {
			
				int totalMoney = resultClass.getTotal_money() - exchangeMoney;
			
				if ( totalMoney < 0){
					exchangeResult = 0;
					return ERROR;
				} else {
					paramClass.setId(id);
					paramClass.setTotal_money(totalMoney);
				
					sqlMapper.update("account.updateExchange", paramClass);
							
					exchangeResult = 1;
					return SUCCESS;
				}
			}
		}
				
	}

	@Override
	public void setSession(Map session) {
		this.session = session;
	}
	public Map getSession() {
		return session;
	}

	public int getExchangeMoney() {
		return exchangeMoney;
	}

	public void setExchangeMoney(int exchangeMoney) {
		this.exchangeMoney = exchangeMoney;
	}

	public int getExchangeResult() {
		return exchangeResult;
	}

	public void setExchangeResult(int exchagneResult) {
		this.exchangeResult = exchagneResult;
	}
	

}
